﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.SQLDispatcherService.Configuration;

namespace A2DFramework.SQLDispatcherService.SimpleADOdotNetDispatcher
{
    public class DBSelector
    {
        public static DB SelectDB(string sql, string region)
        {
            bool redirect2WritableDB = false;
            sql = sql.Trim().TrimStart('\r').TrimStart('\n');
            if (sql.IndexOf("UPDATE", StringComparison.OrdinalIgnoreCase) >= 0)
                redirect2WritableDB = true;
            if (sql.IndexOf("DELETE", StringComparison.OrdinalIgnoreCase) >= 0)
                redirect2WritableDB = true;
            if (sql.IndexOf("INSERT", StringComparison.OrdinalIgnoreCase) >= 0)
                redirect2WritableDB = true;
            if (sql.IndexOf("--WRITE", StringComparison.OrdinalIgnoreCase) == 0)    //强制sql方式进入写db操作
                redirect2WritableDB = true;

            if (redirect2WritableDB)
                return Configuration.SQLDispatcherConfiguration.WritableDB;

            if (region == null || region.Length == 0)       //from normal read dbs
            {
                int random = GenerateRandomNumber();
                int dbIndex = random % Configuration.SQLDispatcherConfiguration.ReadDBs.Count;
                return Configuration.SQLDispatcherConfiguration.ReadDBs[dbIndex];
            }

            DedicatedRegion r = Configuration.SQLDispatcherConfiguration.DedicatedRegions.Find(t => t.Region.Equals(region, StringComparison.OrdinalIgnoreCase));
            if (r == null)
                throw new Exception("No such Dedicated Region Identifier.");

            {
                int random = GenerateRandomNumber();
                int dbIndex = random % r.DBs.Count;
                return r.DBs[dbIndex];
            }
        }

        private static int GenerateRandomNumber()
        {
            Random Random1 = new Random();
            //产生0到1000的随机数
            int i1 = Random1.Next(0, 1001);
            return i1;
        }
    }
}
